package com.shadt.core.controller;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 解决js跨域请求数据
 * 
 * @author liusongren
 *
 */
@Controller
@RequestMapping("/crossDoMain")
public class CrossDomain extends BaseController {

	/**
	 * 解决js跨域请求
	 * 
	 * @param httpUrl
	 * @param key
	 * @param value
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping("/domain")
	public String domain(HttpServletRequest req, String httpUrl, String key, String value) {
		Map<String, String[]> map = req.getParameterMap();
		Set<Entry<String, String[]>> set = map.entrySet();
		Iterator<Entry<String, String[]>> it = set.iterator();
		String params = "";
		while (it.hasNext()) {
			Entry<String, String[]> entry = it.next();
			if(!entry.getKey().equals("httpUrl")){
				params+=entry.getKey()+"=";
				String[] values =entry.getValue();
				for (int i = 0; i < values.length; i++) {
					params += values[i];
				}
				if(it.hasNext()){
					params +="&";
				}
			}
		}
		httpUrl += "?" + params;
		System.out.println("访问路径："+httpUrl);
		BufferedReader reader = null;
		String result = null;
		StringBuffer sbf = new StringBuffer();
		try {
			URL url = new URL(httpUrl);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("POST");
			connection.connect();
			InputStream is = connection.getInputStream();
			reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			String strRead = null;
			while ((strRead = reader.readLine()) != null) {
				sbf.append(strRead);
				sbf.append("\r\n");
			}
			reader.close();
			result = sbf.toString();
		} catch (Exception e) {
			System.out.println("跨域请求异常！");
			e.printStackTrace();
			
		}
		return result;
	}
}
